package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportServiceMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportServiceMapper reportServiceMapper;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;


    //--1--营业额数据统计
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        //--1、时间区间
        List<LocalDate> dateList = new ArrayList<>();
        List<Double> turnoverList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin=begin.plusDays(1);   //开始日期--累加
            dateList.add(begin);       //不等于结束日期，就加入集合
        }

        //--2、遍历时间，查询当天总金额
        dateList.forEach(date->{
            Map param=new HashMap();
            param.put("time",date);
            param.put("status", Orders.COMPLETED);        //状态5:已完成

            //使用map集合，多条件查询，考虑复用
            Double amount=orderMapper.sumByMap(param);    //查询当天总金额
            turnoverList.add(amount);
        });

        //--3、封装VO              例如：2022-10-01,2022-10-02,2022-10-03
        //StringUtils.join()-->  //工具类方法：把集合以","分割
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }


    //--2--用户统计接口
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {

        //--1、时间区间
        List<LocalDate> dateList = new ArrayList<>();         //时间
        List<Integer> totalUserList = new ArrayList<>();      //用户总量
        List<Integer> newUserList = new ArrayList<>();        //新增用户
        LocalDate beforeDate=begin;                           //存放初始时间
        dateList.add(begin);

        while (!begin.equals(end)){
            begin=begin.plusDays(1);   //开始日期--累加
            dateList.add(begin);       //不等于结束日期，就加入集合
        }

        //--统计时间区，例如[09-01，09-07]之前的的用户总数,回退1天为‘08-31’
        beforeDate=beforeDate.minusDays(1);

        Map paramMap=new HashMap();
        paramMap.put("begin",beforeDate);
        Integer total=userMapper.countByMap(paramMap);    //之前存在用户

        //--2、遍历时间
        for (LocalDate date : dateList) {
            Map paramMap2=new HashMap();
            paramMap2.put("time",date);
            Integer newUserCount = userMapper.countByMap(paramMap2); //每天的新用户

            total+=newUserCount;
            newUserList.add(newUserCount);
            totalUserList.add(total);    //当天总用户
        }
        return UserReportVO.builder()
                .newUserList(StringUtils.join(newUserList,','))
                .totalUserList(StringUtils.join(totalUserList,','))
                .dateList(StringUtils.join(dateList,','))
                .build();
    }

    //--3--订单统计接口
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //--1、时间区间
        List<LocalDate> dateListList = new ArrayList<>();          //时间列表
        List<Integer> ordersCountList = new ArrayList<>();         //每天订单总数
        List<Integer> validOrdersCountList = new ArrayList<>();    //每天有效订单总数-集合

        Integer totalOrderCount=0;     //订单总数
        Integer validOrderCount=0;     //有效订单总数
        Double orderCompletionRate=0.0;     //订单完成率


        LocalDate beforeDate=begin;    //开始前一天
        dateListList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateListList.add(begin);
        }

        //--2、遍历时间，查询当天总金额
        dateListList.forEach(date->{
            Map param=new HashMap();
            param.put("time",date);
            Integer todayOrderCount=orderMapper.countByMap(param);//当天总量

            param.put("status", Orders.COMPLETED);        //状态5:已完成
            Integer todayValidOrderCount=orderMapper.countByMap(param);//当天有效

            ordersCountList.add(todayOrderCount);
            validOrdersCountList.add(todayValidOrderCount);
        });

        //订单总数  reduce()集合函数---reduce(默认值，聚合规则)
        totalOrderCount=ordersCountList.stream().reduce(0,(a,b)->{
           return a+b;
        });
        //有效订单总数
        validOrderCount=validOrdersCountList.stream().reduce(0,(a,b)->{
            return a+b;
        });
        //订单完成率
        if(totalOrderCount!=0){
            orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount; //Integer.doubleValue()
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateListList,","))
                .validOrderCountList(StringUtils.join(validOrdersCountList,","))
                .orderCountList(StringUtils.join(ordersCountList,","))
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }


    //--4--查询销量排名top10接口
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        //--1、查时间范围内的菜品销量
        //--方式一：DTO
        //List<GoodsSalesDTO> dtoList=orderMapper.selectSumCopiesAndLimit(begin,end);

        //--方式二：Map
        List<Map> dtoList=orderMapper.selectSumCopiesAndLimit(begin,end);
        List<String> nameList = new ArrayList<>();         //菜名
        List<BigDecimal> numberList = new ArrayList<>();      //销量

        //--2、遍历--加入集合
        dtoList.forEach(date->{
            nameList.add((String) date.get("name"));
            numberList.add((BigDecimal) date.get("number"));
        });

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,','))
                .numberList(StringUtils.join(numberList,','))
                .build();
    }

    /**导出近30天的运营数据报表
     * @param response
     **/
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.businessData(LocalDate.now());
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.businessData(LocalDate.now());
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
